package cn.stylefeng.guns.modular.rest.pandian;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicArea;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.service.BasicAreaService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.inventory.entity.MoveDiskDetailed;
import cn.stylefeng.guns.modular.inventory.model.params.MoveDiskDetailedParam;
import cn.stylefeng.guns.modular.inventory.service.MoveDiskDetailedService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.storage.entity.StorageStock;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 库存管理
 */
@Controller
@RequestMapping("/rest/moveDisk")
public class restMoveDiskController extends BaseController {

    @Autowired
    private MoveDiskDetailedService moveDiskDetailedService;

    @Autowired
    private StorageStockService storageStockService;
    
    @Autowired
    private UserAop userAop;

    @Autowired
    private BasicPositionService basicPositionService;

    /**
     * 查询商品总量，品类总量
     */
    @RequestMapping("/findByListGoodsType")
    @ResponseBody
    public ResponseData findByListGoodsType(StorageStockParam storageStockParam){
    	User user = userAop.getUser();
    	if(ToolUtil.isNotEmpty(storageStockParam.getPositionNumber())) {
    		BasicPositionParam basicPositionParam = new BasicPositionParam();
    		basicPositionParam.setPositionNumber(storageStockParam.getPositionNumber());
    		basicPositionParam.setDeliverId(user.getDeliverId());
    		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam, user.getDeptId(),user.getOperateId());
    		if(basicPositionResult == null) {
    			return ResponseData.error("库位不存在！");
    		} else {
    			storageStockParam.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
    		}
    	}
    	
        storageStockParam.setDeliverId(user.getDeliverId());
        storageStockParam.setDeptId(user.getDeptId());
        storageStockParam.setStockstate("在库");
        StorageStockResult ssr = storageStockService.findTotalBySpec(storageStockParam,user.getOperateId());
        //查询品类总量
        StorageStockResult ssr2 = storageStockService.findTotalgoodsTypeBySpec(storageStockParam,user.getOperateId());
        if (ssr2!=null&&ssr!=null) {
            if (!"0".equals(ssr2.getTotalgoodsType())) {
                ssr.setTotalgoodsType(ssr2.getTotalgoodsType());
            }
        }
        //查询库存商品列表
        if(ssr!=null) {
            storageStockParam.setPositionId(ssr.getPositionId());
            List<StorageStockResult> list1 = storageStockService.moveQueryGoods(storageStockParam,user.getOperateId());
            for (StorageStockResult r : list1) {
            	storageStockParam.setGoodsId(r.getGoodsId());
                List<StorageStockResult> list2 = storageStockService.moveDiskFindGoodsList(storageStockParam,user.getOperateId());
                r.setList2(list2);
    		}
            ssr.setList(list1);
        }
        return ResponseData.success(ssr);
    }

    @Autowired
    private BasicAreaService basicAreaService;

    /**
     * 生成动盘单确定
     */
    @RequestMapping("/appsubmit")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData appsubmit(Long[] ids,String[] newbats, String[] truenums,Long goodsId) {
    	User user = userAop.getUser();
    	ResponseData data = new ResponseData();
        List<MoveDiskDetailedParam> stockParamList = new ArrayList<MoveDiskDetailedParam>();
        for (int i = 0; i < ids.length; i++) {
        	MoveDiskDetailedParam detailedParamnew = new MoveDiskDetailedParam();
        	StorageStock storageStock = storageStockService.getById(ids[i]);
        	BasicArea basicArea = basicAreaService.getById(storageStock.getAreaId());
        	try {
            	detailedParamnew.setTrueNum(truenums[i]);
			} catch (Exception e) {
				ResponseData.error("请填写成数量");
			}
        	detailedParamnew.setNewgoodsbatchs(newbats[i]);
        	detailedParamnew.setWarehouseId(storageStock.getWarehouseId());
        	detailedParamnew.setGoodsId(goodsId);
        	detailedParamnew.setGoodsName(storageStock.getGoodsName());
        	detailedParamnew.setGoodsNumber(storageStock.getGoodsNumber());
        	detailedParamnew.setWarehouseName(storageStock.getWarehouseName());
        	detailedParamnew.setAreaId(storageStock.getAreaId());
        	detailedParamnew.setAreaName(basicArea.getAreaName());
        	detailedParamnew.setPositionId(storageStock.getPositionId());
        	detailedParamnew.setPositionNumber(storageStock.getPositionNumber());
        	detailedParamnew.setGoodsbatchs(storageStock.getGoodsbatchs());
        	detailedParamnew.setTrayNumber(storageStock.getTrayNumber());
        	detailedParamnew.setNum(storageStock.getNum());
        	detailedParamnew.setCreateUsername(user.getName());
        	stockParamList.add(detailedParamnew);
		}
        for (MoveDiskDetailedParam s : stockParamList) {
        	if (ToolUtil.isEmpty(s.getTrueNum())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                data.setMessage("请填写成数量");
        		data.setSuccess(false);
        		return data;
			}
        	BigDecimal as = new BigDecimal(0);
        	BigDecimal num = new BigDecimal(s.getNum());
        	BigDecimal trueNum = new BigDecimal(s.getTrueNum());
        	if (trueNum.compareTo(as)==-1) {
                data.setMessage("不能小于0");
        		data.setSuccess(false);
        		return data;
			}
            
        	if(num.compareTo(trueNum) != 0) {
	            //新增动盘单明细
            	if(trueNum.compareTo(as) == 0) {
            		s.setInventory("缺失");
            	} else if(trueNum.compareTo(num) == -1) {
            		s.setInventory("缺少");
            	} else if(trueNum.compareTo(num) == 1) {
            		s.setInventory("多出");
            	} 
                s.setDeliverId(user.getDeliverId());

                boolean flag = storageStockService.correctNew(s,user);//修改库存
                if (!flag) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
                	return ResponseData.error("库存发生变动，请重新操作");
        		} 
        	} 
		}
        return ResponseData.success();
    }

    /**
     * 新增
     */
    @RequestMapping("/addStorage")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData addStorage(MoveDiskDetailedParam pandianChoupanDetailedParam) {
    	User user = userAop.getUser();
    	if (ToolUtil.isEmpty(pandianChoupanDetailedParam.getTrueNum())) {
    		return ResponseData.error("请填写成数量");
		}
    	BigDecimal as = new BigDecimal(0);
    	BigDecimal trueNum = new BigDecimal(pandianChoupanDetailedParam.getTrueNum());
    	if (trueNum.compareTo(as)==-1) {
    		return ResponseData.error("不能小于0");
		}
    	
        //新增动盘单明细
    	if(ToolUtil.isEmpty(pandianChoupanDetailedParam.getNewgoodsbatchs())) {
    		pandianChoupanDetailedParam.setNewgoodsbatchs(DateUtil.getDate());
    	}
    	if(ToolUtil.isEmpty(pandianChoupanDetailedParam.getGoodsbatchs())) {
    		pandianChoupanDetailedParam.setGoodsbatchs(pandianChoupanDetailedParam.getNewgoodsbatchs().replaceAll("-", ""));
    	}
    	pandianChoupanDetailedParam.setNum("0");
    	pandianChoupanDetailedParam.setInventory("新增");
    	pandianChoupanDetailedParam.setDeliverId(user.getDeliverId());
    	pandianChoupanDetailedParam.setCreateUsername(user.getName());
        boolean flag = storageStockService.correctNew(pandianChoupanDetailedParam,user);//修改库存
        if (!flag) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
        	return ResponseData.error("后台异常，请重新操作");
		} 
        return ResponseData.success();
    }

    /**
     * 根据商品id查询商品
     */
    @RequestMapping("/findByGoods")
    @ResponseBody
    public ResponseData findByGoods(StorageStockParam stockParam){
    	User user = userAop.getUser();
        stockParam.setDeliverId(user.getDeliverId());
        stockParam.setDeptId(user.getDeptId());
        stockParam.setStockstate("在库");
        StorageStockResult ssr2 = storageStockService.findByGoods(stockParam,user.getOperateId());
        if(ssr2 != null) {
            List<StorageStockResult> list1 = storageStockService.totalGoodsVolumeList(stockParam,user.getOperateId());
            for (StorageStockResult r : list1) {
            	stockParam.setPositionId(r.getPositionId());
                List<StorageStockResult> list2 = storageStockService.moveDiskFindGoodsList(stockParam,user.getOperateId());
                r.setList2(list2);
    		}
            ssr2.setList(list1);
        }
        return ResponseData.success(ssr2);
    }

    /**
     *点击处理按钮
     * @param dealList
     * @return
     */
    @RequestMapping("/deleteList")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData deleteList(MoveDiskDetailedParam moveDiskDetailedParam) {
    	User user = userAop.getUser();
    	ResponseData data = new ResponseData();
    	MoveDiskDetailed moveDiskDetailed = moveDiskDetailedService.getById(moveDiskDetailedParam.getId());
    	if (moveDiskDetailed ==null || "已处理".equals(moveDiskDetailed.getInventory())) {
        	data.setSuccess(false);
        	data.setMessage("已被其它人员处理");
        	return data;
		}
    	moveDiskDetailed.setInventory("已处理");
    	moveDiskDetailed.setDealPerson(user.getName());//盘点处理人
        moveDiskDetailed.setDealTime(DateUtil.getDate());//盘点处理时间
        MoveDiskDetailedParam ddp = new MoveDiskDetailedParam();
        ToolUtil.copyProperties(moveDiskDetailed, ddp);
        moveDiskDetailedService.update(ddp);
        boolean flag = storageStockService.correctNew(ddp,user);//修改库存
        if (!flag) {
        	moveDiskDetailedService.delete(ddp);
        	return ResponseData.error("库存发生变动，请重新操作");
		} else {
	        return ResponseData.success("处理完成");
		}
    }
    
    /**
     * 查询商品位置
     */
    @RequestMapping("/kucunlist")
    @ResponseBody
    public ResponseData kucunlist(StorageStockParam param){
    	User user = userAop.getUser();
    	param.setDeptId(user.getDeptId());
    	param.setDeliverId(user.getDeliverId());
        return ResponseData.success(storageStockService.findListBySpec(param,user.getOperateId()));
    }


}
